package com.jelly.interceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import com.jelly.entity.WechatUser;
import com.jelly.service.WechatUserService;
import com.jelly.util.TokenUtil;
import com.jelly.util.UserHolder;

public class TokenIntercepor implements HandlerInterceptor {

	
	private WechatUserService wechatUserService;
	

	public TokenIntercepor(WechatUserService wechatUserService) {
		this.wechatUserService = wechatUserService;
	}


	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

		// 判断是否登录
		String token = request.getHeader("token");
		if (ObjectUtils.isEmpty(token)) {
			return false;
		}
		String userId = TokenUtil.getUserId(token);
		WechatUser user = wechatUserService.findById(Long.valueOf(userId));
		if (user == null) { 
			return false;
		}
		UserHolder.setHolder(Long.valueOf(userId));
		return true;
	}


	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		
		UserHolder.remove();
		HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
	}

	
}
